//websocket
var g_websocket;

/* //响应数据 */
var ackJsonData;

//初始化打印服务
//1.1 获取接口实例JCAPI.getInstance（单例模式）
function getInstance() {
  if ('WebSocket' in window) {
    g_websocket = websocketLifePeriod();
  } else {
    console.log('unsupported websocket');
    //return false;
    g_websocket = null;
    return false;
  }

  //保持在线
  setInterval(function () {
    if (g_websocket.readyState === 2 || g_websocket.readyState === 3) {
      getInstance();
    }
  }, 3000);

  return true;
}

function unInitPrintInstance() {
  g_websocket.close();
}

//2.1 打印机连接成功回调onConnectSuccess
function onConnectSuccess(printerName) {
  console.log('连接打印机!');
}

//2.2 打印机断开回调onDisConnect
function onDisConnect(printerName) {
  console.log('打印机断开！');
}

//2.3 打印机上盖变化回调onCoverStatusChange
function onCoverStatusChange(coverStatus) {
  console.log('打印机盒盖有变化！');
}

//2.4 打印机电量变化回调onElectricityChange()
function onElectricityChange(powerLever) {
  console.log('打印机电量有变化！');
}

//2.5 打印机纸张状态变化回调onPaperStatusChange
function onPaperStatusChange(paperStatus) {
  console.log('打印机纸张状态有变化！');
}

//8.1 页打印成功回调onPrintPageCompleted
function onPrintPageCompleted() {
  console.log('页打印状态有变化！');
}

//8.2 打印进度回调onPrintProgress
function onPrintProgress() {
  console.log('打印进度有变化！');
}

//8.3 打印异常回调onAbnormalResponse
function onAbnormalResponse() {
  console.log('打印异常！');
}

//获取所有当前PC上连接的精臣打印机
//3.1 获取打印机列表getAllPrinters()
function getAllPrinters(callbackFunction) {
  //刷新设备时，关闭设备
  //closePrinter();
  var jsonObj = { apiName: 'getAllPrinters' };
  var allDevice = {};

  sendMsg(jsonObj, callbackFunction);
}

//4.图片打印
/*base64Data--图片base64数据
nPrintCount--打印数量
bDenoise--降噪*/
function picturePrint(base64Data, nPrintCount, bDenoise, callbackFunction) {
  var jsonObj = {
    apiName: 'picturePrint',
    parameter: {
      data: base64Data,
      nPrintCount: nPrintCount,
      bDenoise: bDenoise
    }
  };

  sendMsg(jsonObj, callbackFunction);
}

//5.选择并打开需要使用的打印机名称，及端口号
function selectPrinter(printerName, port, callbackFunction) {
  var jsonObj = {
    apiName: 'selectPrinter',
    parameter: { printerName: printerName, port: port }
  };
  sendMsg(jsonObj, callbackFunction);
}

//6.停止打印
function stopPrint(callbackFunction) {
  var jsonObj = { apiName: 'stopPrint' };
  sendMsg(jsonObj, callbackFunction);
}

//7.关闭打印端口

function closePrinter(callbackFunction) {
  var jsonObj = { apiName: 'closePrinter' };
  sendMsg(jsonObj, callbackFunction);
}

//8.设置打印浓度
//nDensity--范围为getDensityScopeApi查询范围
function setPrintDensity(nDensity, callbackFunction) {
  var jsonObj = {
    apiName: 'setPrintDensity',
    parameter: { nDensity: nDensity }
  };
  sendMsg(jsonObj, callbackFunction);
}

//9.设置打印速度
//nSpeed--范围为getSpeedScopeApi查询的范围
function setPrintSpeed(nSpeed, callbackFunction) {
  var jsonObj = { apiName: 'setPrintSpeed', parameter: { nSpeed: nSpeed } };
  sendMsg(jsonObj, callbackFunction);
}

//10.设置打印标贴类型
//nType--间隙：01，黑标：02，连续纸：03，定位孔：04，透明纸：05，随机打印：06
function setPrintLabelType(nType, callbackFunction) {
  var jsonObj = { apiName: 'setPrintLabelType', parameter: { nType: nType } };
  sendMsg(jsonObj, callbackFunction);
}

function setPrintMaterial(nType, callbackFunction) {
  var jsonObj = { apiName: 'setPrintMaterial', parameter: { nType: nType } };
  sendMsg(jsonObj, callbackFunction);
}

//11.设置关机时间
//nType--1：15分钟，2:30分钟，3:60分钟，4：never
function setPrinterAutoShutDownTime(nType, callbackFunction) {
  var jsonObj = {
    apiName: 'setPrinterAutoShutDownTime',
    parameter: { nType: nType }
  };
  sendMsg(jsonObj, callbackFunction);
}

//12.复位打印机
function setPrinterReset(callbackFunction) {
  var jsonObj = { apiName: 'setPrinterReset' };
  sendMsg(jsonObj, callbackFunction);
}

//纸张标定
function setPrintPaperPos(nType, callbackFunction) {
  var jsonObj = { 
  apiName: 'setPrintPaper',
  parameter:{nType:nType}
  };
  sendMsg(jsonObj, callbackFunction);
}

//13.设置打印模式
//nType-1热敏，2碳带
function setPrintMode(nType, callbackFunction) {
  var jsonObj = { apiName: 'setPrintMode', parameter: { nType: nType } };
  sendMsg(jsonObj, callbackFunction);
}

//14.获取打印速度
function getPrintSpeed(callbackFunction) {
  var jsonObj = { apiName: 'getPrintSpeed' };
  sendMsg(jsonObj, callbackFunction);
}

function getPower(callbackFunction) {
  var jsonObj = { apiName: 'getPower' };
  sendMsg(jsonObj, callbackFunction);
}

//15.获取标贴类型
function getPrintLabelType(callbackFunction) {
  var jsonObj = { apiName: 'getPrintLabelType' };

  sendMsg(jsonObj, callbackFunction);
}

//16.获取打印浓度
function getPrintDensity(callbackFunction) {
  var jsonObj = { apiName: 'getPrintDensity' };
  sendMsg(jsonObj, callbackFunction);
}

//17.获取打印机语言
function getPrinterLanguageType(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterLanguageType' };
  sendMsg(jsonObj, callbackFunction);
}

//18.查询关机时间
function getPrinterAutoShutDownTime(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterAutoShutDownTime' };
  sendMsg(jsonObj, callbackFunction);
}

//19.获取打印机序列号
function getPrinterSn(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterSn' };
  sendMsg(jsonObj, callbackFunction);
}

//20.获取硬件版本
function getPrinterHardwareVersion(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterHardwareVersion' };
  var responseData = {};
  sendMsg(jsonObj, callbackFunction);
}

//21.获取软件版本
function getPrinterSoftwareVersion(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterSoftwareVersion' };
  sendMsg(jsonObj, callbackFunction);
}

//获取打印Tag
function getPrinterTagID(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterTagID' };
  sendMsg(jsonObj, callbackFunction);
}

//获取打印次数
function getPrinterTimes(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterTimes' };
  sendMsg(jsonObj, callbackFunction);
}

//获取打印机语言
function setPrinterLanguageType(nType, callbackFunction) {
  var jsonObj = {
    apiName: 'setPrinterLanguageType',
    parameter: { nType: nType }
  };
  sendMsg(jsonObj, callbackFunction);
}

//将图像转换为base64数据，仅供demo测试使用，暂时有问题
function readFileWithBase64(filePath, callbackFunction) {
  var jsonObj = {
    apiName: 'readFileWithBase64',
    parameter: { filePath: filePath }
  };
  sendMsg(jsonObj, callbackFunction);
}

//发送十六进制指令，仅供demo测试使用
function sendData(data, dataSize, callbackFunction) {
  var jsonObj = {
    apiName: 'sendData',
    parameter: { data: data, dataSize: dataSize }
  };
  sendMsg(jsonObj, callbackFunction);
}

//获取打速度印范围
function getSpeedScope(callbackFunction) {
  var jsonObj = { apiName: 'getSpeedScope' };
  sendMsg(jsonObj, callbackFunction);
  return getResult(5, 'getSpeedScope', 'set printer language timeout!');
}

function getConnectPrinter(callbackFunction) {
  var jsonObj = { apiName: 'getConnectPrinter' };
  sendMsg(jsonObj, callbackFunction);
  return getResult(5, 'getConnectPrinter', 'get connect printer timeout!');
}

function getPrinterType(callbackFunction) {
  var jsonObj = { apiName: 'getPrinterType' };
  sendMsg(jsonObj, callbackFunction);
}

//获取浓度范围
function getDensityScope(callbackFunction) {
  var jsonObj = { apiName: 'getDensityScope' };
  sendMsg(jsonObj, callbackFunction);
}

var MessageList = {};
function sendMsg(msg, callback) {
  console.log('sendMsg', msg.apiName);
  MessageList[msg.apiName] = callback;

  var data = JSON.stringify(msg);
  var tryTimes = 10;

  for (var i = 0; i < tryTimes; i++) {
    if (g_websocket.readyState === 1) {
      g_websocket.send(data);
      return;
    }
  }
}

function getPrinterMode(callbackFunction) {
  var jsonObj = { apiName: 'getPrintMode' };
  sendMsg(jsonObj, callbackFunction);
}

function getMacAddress(callbackFunction) {
  var jsonObj = { apiName: 'getMacAddress' };
  sendMsg(jsonObj, callbackFunction);
}

function setLog()
{
	var jsonObj={apiName:'setLog'};
	sendMsg(jsonObj,null);
}

//32.连接回调
function connectCallback(e) {
  ackJsonData = '';
  console.log('success');
}

//33.关闭连接回调
function closeCallback(e) {
  console.log(
    'websocket closed: ' + e.code + ' ' + e.reason + ' ' + e.wasClean
  );
  // globalwebsocket = websocket;
  g_websocket.close();
  //websocketLifePeriod();
  if (e.code == 1005) {
    // globalwebsocket = websocket;
  }
  console.log('closed');
  ackJsonData = '';
}

function binaryData(ev) {
    return JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array(ev.data)));
}

//34.读回调
function readCallback(e) {
  //var callBackInfo = binaryData(e);
  //var callBackInfo = new TextDecoder("utf-8").decode(new Uint8Array(e.data));
  var callBackInfo = e.data;
  console.log('readCallback', callBackInfo);
  ackJsonData = callBackInfo;

  var callbackName;

  if (isJSON(ackJsonData)) {
    var arrParse = JSON.parse(ackJsonData);

    //接口回调
    if (!!MessageList[arrParse.apiName]) {
      MessageList[arrParse.apiName](arrParse);
    }

    //回调分发
    if (arrParse['resultAck']['callback'] != undefined) {
      callbackName = arrParse['resultAck']['callback']['name'];

      if (callbackName == 'onConnectSuccess') {
        var printerName = arrParse['resultAck']['callback']['printerName'];

        onConnectSuccess(printerName);
      } else if (callbackName == 'onDisConnect') {
        var printerName = arrParse['resultAck']['callback']['printerName'];
        onDisConnect(printerName);
      } else if (callbackName == 'onCoverStatusChange') {
        var coverStatus = arrParse['resultAck']['callback']['coverStatus'];
        onCoverStatusChange(coverStatus);
      } else if (callbackName == 'onElectricityChange') {
        var powerLever = arrParse['resultAck']['callback']['powerLever'];
        onElectricityChange(powerLever);
      } else if (callbackName == 'onPaperStatusChange') {
        var paperStatus = arrParse['resultAck']['callback']['paperStatus'];
        onPaperStatusChange(paperStatus);
      } else if (callbackName == 'onPrintPageCompleted') {
        onPrintPageCompleted();
      } else if (callbackName == 'onPrintProgress') {
        onPrintProgress();
      } else if (callbackName == 'onAbnormalResponse') {
        onAbnormalResponse();
      }
	  else {
        console.log('unknow callback api!');
      }
    }

    ackJsonData = '';
  }
}
//35.错误回调
function errorCallback(e) {
  //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
  console.log(e.data);
}

//0.初始化sdk
//
function initSdk(fontDir) {
  var jsonObj = {
    apiName: 'initSdk',
    parameter: {
	  fontDir: fontDir,
    }
  };
  sendMsg(jsonObj, null);
}
//13.设置打印模式
//nType-1热敏，2碳带
function setPrintMode(nType, callbackFunction) {
  var jsonObj = { apiName: 'setPrintMode', parameter: { nType: nType } };
  sendMsg(jsonObj, callbackFunction);
}
/**
 * 1.开始打印任务
 * @param {number} printDensity 打印浓度
 * @param {number} printLabelType 纸张类型
 * @param {number} printMaterial 材质
 * @param {number} printMode 打印模式
 * @param {number} count 总打印张数
 * @param {*} callbackFunction 回调函数
 */
function startJob(printDensity, printLabelType, printMode, count, callbackFunction) {
  var jsonObj = {
    apiName: 'startJob',
    parameter: {
      printDensity: printDensity,
      printLabelType: printLabelType,
      printMode: printMode,
      count: count
    }
  };
  sendMsg(jsonObj, callbackFunction);
}

//2.提交打印任务commitJob
//打印开始

function commitJob(printData,printerImageProcessingInfo,callbackFunction) {
   var printDataJson = eval('(' + printData + ')');
   var printerImageProcessingInfoJson = eval('(' + printerImageProcessingInfo + ')');
  var jsonObj = {
    apiName: 'commitJob',
    parameter: {
	  printData: printDataJson,
	  printerImageProcessingInfo:printerImageProcessingInfoJson['printerImageProcessingInfo'],
    }
  };
  sendMsg(jsonObj, callbackFunction);
}

//3.结束打印任务endJob
//发送打印总结束
function endJob(callbackFunction) {
  var jsonObj = { apiName: 'endJob' };
  sendMsg(jsonObj, callbackFunction);
  //return getResult(5, 'endJob', 'set printer language timeout!');
}

//4.取消打印任务cancleJob
//发送取消打印指令

function cancleJob(callbackFunction) {
  var jsonObj = { apiName: 'stopPrint' };
  sendMsg(jsonObj, callbackFunction);
  //return getResult(5, 'cancleJob', 'set printer language timeout!');
}

//42.7.1 图像绘制drawImage
//处理打印图像
function drawImage(base64, x, y, width, height, rotate) {
  var jsonObj = {
    apiName: 'drawImage',
    parameter: {
      data: base64,
      x: x,
      y: y,
      width: width,
      height: height,
      orientation: rotate
    }
  };
  sendMsg(jsonObj, null);
  //return getResult(5, 'drawImage', 'set printer language timeout!');
}

function updateFirmware(fileName,strSwVersion,strCrc,strHwVersion,nPrinterType) {
  var jsonObj = {
    apiName: 'updateFirmware',
    parameter: {
      fileName: fileName,
      strSwVersion: strSwVersion,
      strCrc: strCrc,
	  strHwVersion:strHwVersion,
	  nPrinterType:nPrinterType
    } 
  };
  sendMsg(jsonObj, null);
  //return getResult(5, 'drawImage', 'set printer language timeout!');
}

function cancleUpdateFirmware() {
  var jsonObj = { apiName: 'cancleUpdateFirmware' };
  sendMsg(jsonObj, null);
  //return getResult(5, 'drawImage', 'set printer language timeout!');
}

function updateFrontpanel(fileName,strSwVersion,strCrc) {
  var jsonObj = {
    apiName: 'updateFrontpanel',
    parameter: {
      fileName: fileName,
      strSwVersion: strSwVersion,
      strCrc: strCrc
    } 
  };
  sendMsg(jsonObj, null);
  //return getResult(5, 'drawImage', 'set printer language timeout!');
}

function cancleUpdateFrontpanel() {
  var jsonObj = { apiName: 'cancleUpdateFrontpanel' };
  sendMsg(jsonObj, null);
  //return getResult(5, 'drawImage', 'set printer language timeout!');
}

function initImageProcessing(data)//初始化图像字体
{
	 var jsonObj = {
    apiName: 'initImageProcessing',
    parameter: {
      fontFamilyPath:data,
	  defaultFamilyPath:data
    } 
  };
  console.log('sendMsg111', jsonObj);
  sendMsg(jsonObj, null);
}

//暂停打印
function pausePrint(callbackFunction) {
  var jsonObj = { apiName: 'pausePrint' };
  sendMsg(jsonObj, callbackFunction);
}

//启动打印
function resumePrint(callbackFunction) {
  var jsonObj = { apiName: 'resumePrint' };
  sendMsg(jsonObj, callbackFunction);
}

/***********************第三方绘制打印接口******************************/
function initSdk(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'initSdk',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//创建画板
function InitDrawingBoard(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'InitDrawingBoard',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制文本
function DrawLableText(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableText',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制一维码
function DrawLableBarCode(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableBarCode',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制二维码
function DrawLableQrCode(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableQrCode',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制线条
function DrawLableLine(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableLine',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制图形
function DrawLableGraph(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableGraph',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//绘制图像
function DrawLableImage(json,callbackFunction)
{
	var jsonObj = {
    apiName: 'DrawLableImage',
    parameter: json
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//生成预览图
function generateImagePreviewImage(displayScale,callbackFunction)
{
	var jsonObj = {
    apiName: 'generateImagePreviewImage',
	displayScale: displayScale
  };
  
  sendMsg(jsonObj, callbackFunction);
}

//图片打印
function picturePrint(imgBase64,callbackFunction)
{
	var jsonObj = {
    apiName: 'picturePrint',
	parameter: imgBase64
  };
  
  sendMsg(jsonObj, callbackFunction);
}


//打开链接及回调
function websocketLifePeriod() {

  var websocket;
  websocket = new WebSocket('ws://127.0.0.1:37989');
  //websocket.binaryType = 'arraybuffer';
  websocket.onerror=function (evt) 
     {//since there is an error, sockets will close so...
       sok.onclose=function(e){
	 console.log("WebSocket Error: " , e);}}
		   
  websocket.proxy_read_timeout = 10000;
  websocket.binaryType = "arraybuffer";

  websocket.onopen = connectCallback;

  websocket.onclose = closeCallback;

  websocket.onmessage = readCallback;

  websocket.onerror = errorCallback;

  console.log(websocket);

  return websocket;
}

// 调用结果
function getResult(tryTime, apiName, errInfo) {
  tryTimes = tryTime;

  let result = {};
  while (tryTimes--) {
    if (!isJSON(ackJsonData)) continue;

    var arrParse = JSON.parse(ackJsonData);
    if (arrParse['apiName'] === apiName) {
      result = arrParse['resultAck'];
      break;
    }
  }

  if (tryTimes <= 0) {
    result['result'] = false;
    result['errorCode'] = 0x12;
    result['info'] = errInfo;
  }
  return result;
}

function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }

    } catch (e) {
      //console.log('error：'+str+'!!!'+e);
      return false;
    }

  }

  console.log('It is not a string!');
}
